package com.tianji.promotion.lock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.EnumMap;
import java.util.function.Function;

@Component
public class LogFactory {

    @Autowired
    private RedissonClient redissonClient;

//    @FunctionalInterface
//    interface LockCreator{
//        public RLock apply(String lockNme);
//    }

    private EnumMap<LockType, Function<String, RLock>> map = new EnumMap<>(LockType.class);

    @PostConstruct
    public void postConstruct(){
        map.put(LockType.RE_ENTRANT_LOCK, redissonClient::getLock);
        map.put(LockType.READ_LOCK, lockNme -> redissonClient.getReadWriteLock(lockNme).readLock());
        map.put(LockType.WRITE_LOCK, lockNme -> redissonClient.getReadWriteLock(lockNme).writeLock());
        map.put(LockType.FAIR_LOCK,  redissonClient::getFairLock);
    }
    {



//        map.put(LockType.FAIR_LOCK, new LockCreator() {
//            @Override
//            public RLock apply(String lockNme) {
//                return redissonClient.getFairLock(lockNme);
//            }
//        });

    }

    public RLock getLock(LockType lockType, String lockNme){
        Function<String, RLock> lockCreator = map.get(lockType);
        return lockCreator.apply(lockNme);
//        if(lockType == LockType.RE_ENTRANT_LOCK){
//            return  redissonClient.getLock(lockNme);
//        }else if(lockType == LockType.FAIR_LOCK){
//            return  redissonClient.getFairLock(lockNme);
//        }else if(lockType == LockType.READ_LOCK){
//            return redissonClient.getReadWriteLock(lockNme).readLock();
//        } else if(lockType == LockType.WRITE_LOCK){
//            return redissonClient.getReadWriteLock(lockNme).writeLock();
//        } else{
//            throw new BizIllegalException("不支持的锁类型");
//        }
    }

}
